package demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * RestTemplate 配置类
 * Springboot 必须要初始化 RestTemplate 配置类才能使用 此 http client 工具
 * @author ZhengDing
 * @date 2022/2/27 13:55
 */

@Configuration
public class RestTemplateConfig {
    
    /**
     * http 请求工厂对象
     * 用于配置 基础请求参数
     * @return
     */
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000); //单位为ms
        factory.setConnectTimeout(5000); //单位为ms
        return factory;
    }
    
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}
